package com.atguigu.service;

import com.atguigu.mapper.UserMapper;
import com.atguigu.pojo.User;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private UserMapper userMapper;


    @Override
    public PageInfo<User> getUserPageList(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> listUser = userMapper.getUserPageList();
        return new PageInfo<User>(listUser);
    }

    @Override
    public void insertUser(User user) {
        userMapper.insertUser(user);
    }

    @Override
    public void updateUser(User user) {
        redisTemplate.delete("user::" + user.getId());
        userMapper.updateUser(user);
    }

    @Override
    public void deleteUserById(int id) {
        redisTemplate.delete("user::" + id);
        userMapper.deleteUserById(id);
    }

    @Override
    @Caching
    public User findUserById(int id) {
        String key = "user::" + id;
        User user = null;
        long start = System.currentTimeMillis();
        if (redisTemplate.hasKey(key)) {
            user = (User) redisTemplate.opsForValue().get(key);
        } else {
            user = userMapper.findUserById(id);
            redisTemplate.opsForValue().set(key, user);
        }


        long end = System.currentTimeMillis();
        System.out.println("耗时:" + (end - start));
        return user;
    }
}
